<template>
  <div>
    <!-- 新增按钮 -->
    <el-button type="primary" size="small" @click="handleAdd" style="margin-bottom: 10px">
      新增教育背景
    </el-button>

    <!-- 教育背景列表 -->
    <h3>教育背景列表</h3>
    <el-table :data="educationList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="schoolName" label="学校名称" align="center" />
      <el-table-column label="学历" align="center">
        <template #default="scope">
          {{ educationMap[scope.row.education] || scope.row.education || '未知' }}
        </template>
      </el-table-column>
      <el-table-column prop="major" label="专业" align="center" />
      <el-table-column label="开始日期" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.endDate) }}
        </template>
      </el-table-column>
      <el-table-column label="学位" align="center">
        <template #default="scope">
          {{ degreeMap[scope.row.degree] || scope.row.degree || '未填写' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="form.eduId ? '编辑教育背景' : '新增教育背景'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="90px">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="form.schoolName" placeholder="请输入学校名称" />
        </el-form-item>

        <el-form-item label="学历" prop="education">
          <el-select v-model="form.education" placeholder="请选择学历" style="width: 100%">
            <el-option
              v-for="(label, value) in educationMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="major">
          <el-input v-model="form.major" placeholder="请输入专业" />
        </el-form-item>

        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="学位" prop="degree">
          <el-select v-model="form.degree" placeholder="请选择学位" style="width: 100%">
            <el-option
              v-for="(label, value) in degreeMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getEducationByEmpId, addEducation, updateEducation, delEducation } from "@/api/hrm/education";

// 日期格式化函数（可复用）
function formatDate(dateStr) {
  if (!dateStr) return '—';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '—';
  return date.toISOString().split('T')[0]; // 格式化为 yyyy-MM-dd
}

export default {
  name: "EmployeeEducationList",
  props: {
    empId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      educationList: [],
      loading: false,
      form: {
        eduId: null,
        schoolName: "",
        education: "",
        major: "",
        startDate: "",
        endDate: "",
        degree: ""
      },
      // 学历映射
      educationMap: {
        博士: "博士",
        硕士: "硕士",
        本科: "本科",
        大专: "大专"
      },
      // 学位映射
      degreeMap: {
        博士: "博士",
        硕士: "硕士",
        学士: "学士"
      },
      rules: {
        schoolName: [{ required: true, message: "请输入学校名称", trigger: "blur" }],
        education: [{ required: true, message: "请选择学历", trigger: "change" }],
        major: [{ required: true, message: "请输入专业", trigger: "blur" }],
        startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }],
        endDate: [{ required: true, message: "请选择结束日期", trigger: "change" }],
        degree: [{ required: true, message: "请选择学位", trigger: "change" }]
      }
    };
  },
  methods: {
    formatDate, // 挂载到 methods，供模板使用

    async loadData() {
      this.loading = true;
      try {
        const res = await getEducationByEmpId(this.empId);
        this.educationList = Array.isArray(res.data) ? res.data : [];
      } catch (error) {
        this.$message.error("获取教育背景失败");
        console.error("获取教育背景失败:", error);
        this.educationList = [];
      } finally {
        this.loading = false;
      }
    },

    handleAdd() {
      this.resetForm();
      this.dialogVisible = true;
    },

    handleEdit(row) {
      this.form = { ...row };
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确定删除该教育背景吗？", "提示", {
        type: "warning"
      }).then(async () => {
        try {
          await delEducation(row.eduId); // ✅ 正确调用
          this.$message.success("删除成功");
          this.loadData();
        } catch (error) {
          this.$message.error("删除失败");
        }
      }).catch(() => {});
    },

    resetForm() {
      this.$refs.form?.resetFields?.();
      this.form = {
        eduId: null,
        schoolName: "",
        education: "",
        major: "",
        startDate: "",
        endDate: "",
        degree: ""
      };
    },

    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return;

        try {
          const data = { ...this.form, empId: this.empId };

          if (this.form.eduId) {
            await updateEducation(data);
            this.$message.success("更新成功");
          } else {
            await addEducation(data);
            this.$message.success("新增成功");
          }

          this.dialogVisible = false;
          this.loadData();
        } catch (error) {
          this.$message.error("保存失败");
        }
      });
    }
  },
  watch: {
    empId: {
      immediate: true,
      handler(newVal) {
        if (newVal) this.loadData();
      }
    }
  }
};
</script>

<style scoped>
h3 {
  margin-bottom: 10px;
}
</style>
